function(download_and_decompress url filename sha256_checksum decompress_dir)
  if(EXISTS ${filename})
    file(SHA256 ${filename} CHECKSUM_VARIABLE)
  endif()
  if(NOT EXISTS ${filename} OR NOT CHECKSUM_VARIABLE STREQUAL sha256_checksum)
    message("Downloading file from ${url} to ${filename} ...")
    file(DOWNLOAD ${url} "${filename}.tmp" SHOW_PROGRESS EXPECTED_HASH SHA256=${sha256_checksum})
    file(RENAME "${filename}.tmp" ${filename})
  endif()
  if(NOT EXISTS ${decompress_dir})
    file(MAKE_DIRECTORY ${decompress_dir})
  endif()
  message("Decompress file ${filename} ...")
  execute_process(COMMAND ${CMAKE_COMMAND} -E tar -xf ${filename} WORKING_DIRECTORY ${decompress_dir})
endfunction()

function(get_osx_architecture)
  if (CMAKE_OSX_ARCHITECTURES STREQUAL "arm64")
    set(CURRENT_OSX_ARCH "arm64" PARENT_SCOPE)
  elseif(CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64")
    set(CURRENT_OSX_ARCH "x86_64" PARENT_SCOPE)
  else()
    set(CURRENT_OSX_ARCH ${CMAKE_HOST_SYSTEM_PROCESSOR} PARENT_SCOPE)
  endif()
endfunction()

function(detect_host_triplet outvar)
  string(TOLOWER "${CMAKE_HOST_SYSTEM_NAME}" host_triplet_system)
  string(TOLOWER "${CMAKE_HOST_SYSTEM_PROCESSOR}" host_triplet_arch)
  if(host_triplet_system STREQUAL "darwin")
    set(host_triplet_system "osx")
  endif()
  message("host_triplet_system: ${host_triplet_system}")
  message("host_triplet_arch: ${host_triplet_arch}")
  if(host_triplet_arch MATCHES "(amd64|x86_64)")
    set(host_triplet_arch "x64")
  elseif(host_triplet_arch MATCHES "i[3456]86")
    set(host_triplet_arch "x86")
  elseif(host_triplet_arch MATCHES "(aarch64|armv8l|arm64)")
    set(host_triplet_arch "arm64")
  else()
    message(FATAL_ERROR "Unrecognized CMAKE_HOST_SYSTEM_PROCESSOR: ${CMAKE_HOST_SYSTEM_PROCESSOR}")
  endif()
  set(${outvar} "${host_triplet_arch}-${host_triplet_system}" PARENT_SCOPE)
endfunction()

if (APPLE)
  set(CMAKE_OSX_DEPLOYMENT_TARGET 12.0)
  get_osx_architecture()
endif (APPLE)
